package com.xxx.springboot.service.impl;

import cn.hutool.Hutool;
import com.alibaba.fastjson.JSONObject;
import com.xxx.springboot.pojo.entity.User;
import com.xxx.springboot.mapper.UserMapper;
import com.xxx.springboot.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.springboot.util.HutoolUtil;
import com.xxx.springboot.util.UUIDUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public String createQrImg() {
        String uuid = UUIDUtils.createUUID32();
        User user = new User();
        user.setUuid(uuid);
        user.setState(0);
        user.setCreateTime(new Date());
        save(user);
        return uuid;
    }

    @Override
    public String bindUserIdAndToken(Integer userId, String token, Integer projId) throws Exception {

        User user = this.lambdaQuery().eq(User::getUuid, token).one();
        if(null == user){
            throw  new Exception("错误的请求！");
        }

        Date createDate = new Date(user.getCreateTime().getTime() + (1000 * 60 * 10));
        Date nowDate = new Date();
        if(nowDate.getTime() > createDate.getTime()){ //当前时间大于校验时间

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",500);
            jsonObject.put("msg","二维码失效！");
            WebSocketServer.sendInfo(jsonObject.toJSONString(), token);

            throw  new Exception("二维码失效！");
        }

        user.setLoginTime(new Date());
        user.setUserId(userId);

        boolean i = this.lambdaUpdate().update(user);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","ok");
        jsonObject.put("userId",userId);
        if(projId!=null){
            jsonObject.put("projId",projId);
        }
        WebSocketServer.sendInfo(jsonObject.toJSONString(),token);

        if(i){
            return null;
        }else{
            throw  new Exception("服务器异常！");
        }
    }

}
